﻿using Bll;
using Entity;
using Model;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Utils;
using Vote.Filters;
using Vote.Models;

namespace Vote.Controllers
{
    public class HomeController : Controller
    {
        public static int limitVoteNum = int.Parse(ConfigurationManager.AppSettings["limitVoteNum"]);
        public static string apiJson = ConfigurationManager.AppSettings["APIJSON"].ToString();
        public static string weixinDomain = ConfigurationManager.AppSettings["WeixinDomain"].ToString();
        public ActionResult Index()
        {
            //VoteNumber test = new VoteNumber();
            //test.CreateTime = DateTime.Now;
            //test.EndTime = DateTime.Now.AddMonths(1);
            //test.Name = "test";
            //test.Num = 10;
            //test.StartTime = DateTime.Now.AddDays(1);
            //test.IsEffective = true;


            //VoteNumber test2 = new VoteNumber();
            //test2.CreateTime = DateTime.Now;
            //test2.EndTime = DateTime.Now.AddMonths(1);
            //test2.Name = "test2";
            //test2.Num = 5;
            //test2.StartTime = DateTime.Now.AddDays(2);
            //test.IsEffective = false;

            //BllVoteNumber.AddNewEntity<VoteNumber>("VoteNumber", test);
            //BllVoteNumber.AddNewEntity<VoteNumber>("VoteNumber", test2);
            //VoteNumber number = BllVoteNumber.SelectEntity<VoteNumber>("VoteNumber", 1);
            //number.Name="fuck";
            //BllVoteNumber.UpdateEntity<VoteNumber>("VoteNumber",number);
            //BllVoteNumber.UpdateEntityBySql("VoteNumber", "update VoteNumber set name='good' where id=1");
            //List<VoteNumber> numberList = BllVoteNumber.SelectEntityBySql<VoteNumber>("VoteNumber", "select * from VoteNumber");
            //List<string> stringList = BllVoteNumber.SelectSingleValueBySql("VoteNumber", "select name from VoteNumber");
            //foreach (string lt in stringList)
            //{
            //    string name = lt;
            //}

            //List<fuck> numberList = BllVoteNumber.SelectEntityBySql<fuck>("VoteNumber", "select id,name from VoteNumber");
            //(tableName, conditionFiledValue, currentPage, pageSize, orderByFiled, desc, out totalPage);

            //Dictionary<string, string> dic = new Dictionary<string, string>();
            ////dic.Add("name","test");
            //int totalPage = 0;
            //List<VoteNumber> pageList = BllVoteNumber.SelectEntityInfoByQueryWithPager<VoteNumber>("VoteNumber", dic, 1, 1, "id", false, out totalPage);


                return View();
        }

        #region 投票，搜索，详情
        /// <summary>
        /// 投票页面(电脑端要把WeixinFilter过滤器注释掉)
        /// </summary>
        /// <returns></returns>
      
        [WeixinFilter]
        public ActionResult Votes(int VoteNumberId = -1,int page=1,double scrollNum=0)
        {

            //电脑端模拟微信登陆把这个注释打开
            //Session["OpenId"] = "o8f7iwvE4y-jPi55QXeAx85u5QiY";

            #region 是否关注

             string openId_ = Session["OpenId"].ToString();

             bool isSubscribe = IsSubscribe(openId_);

             ViewBag.isSubscribe = isSubscribe;
               
            #endregion

            #region 查询用
            #region 先从缓存读取,查看是否有对应的用户
            if (Session["OpenId"] != null)
            {
                string openId = Session["OpenId"].ToString();
                var redisClient = RedisManager.GetClient();
                var userInfoModelList = redisClient.GetTypedClient<UserInfoForVote>();
                List<UserInfoForVote> listUserInfo = userInfoModelList.GetAll().ToList();
                foreach (UserInfoForVote model in listUserInfo)
                {
                    if (!string.IsNullOrEmpty(model.OpenId) && model.OpenId.Equals(openId))
                    {
                        Session["userName"] = model.UserName;
                        break;
                    }
                }
            }
            #endregion

            #endregion
            List<VoteNumber> VoteNu = RedisCommon.GetListByRedis<VoteNumber>();
            VoteNumber vn = new VoteNumber();
            if (VoteNu != null && VoteNu.Count > 0)
            {
                vn = VoteNu.FirstOrDefault();
            }
            long xxxx = vn.Id;
            VoteNumberId = xxxx.ConToInt();
            string userName = null;
            if (Session["userName"] != null)
            {
                userName = Session["userName"].ToString();
            }
            List<VoteShowModel> ListVoteShow = new List<VoteShowModel>();
            ListVotesShowModel ListShowModel = new ListVotesShowModel();
            PageModel<VoteShowModel> xx = new PageModel<VoteShowModel>();
            xx.PageSize = 6 * page;
            xx.PageIndex = 1;

            RedisCommon.GetPageListByRedisConditions<VoteShowModel>(ref xx, VoteNumberId, userName, limitVoteNum);
            ListVoteShow = xx.ObjectList;

            #region  开始、结束时间、剩余票数
            ListShowModel.RemainVotes = BllVoteNumber.GetRemainVotes(VoteNumberId, userName, limitVoteNum);
            ListShowModel.StartTime = vn.StartTime.ToString("yyyy-MM-dd");
            ListShowModel.EndTime = vn.EndTime.ToString("yyyy-MM-dd");
            ListShowModel.VoteModel = ListVoteShow;
            #endregion

            ViewBag.Model = ListShowModel;
            ViewBag.VoteNumbers = VoteNu;
            ViewBag.VoteNumberId = VoteNumberId;
            ViewBag.page = page;
            ViewBag.scrollNum = scrollNum;

            return View();
        }


        //分页
        public JsonResult PageList(int PageIndex, int VoteNumberId)
        {
            #region 查询用户
            #region 先从缓存读取,查看是否有对应的用户
            if (Session["OpenId"] != null)
            {
                string openId = Session["OpenId"].ToString();
                var redisClient = RedisManager.GetClient();
                var userInfoModelList = redisClient.GetTypedClient<UserInfoForVote>();
                List<UserInfoForVote> listUserInfo = userInfoModelList.GetAll().ToList();
                foreach (UserInfoForVote model in listUserInfo)
                {
                    if (!string.IsNullOrEmpty(model.OpenId)&&model.OpenId.Equals(openId))
                    {
                        Session["userName"] = model.UserName;
                        break;
                    }
                }
            }
            #endregion

            #endregion

            string userName = null;
            if (Session["userName"] != null)
            {
                userName = Session["userName"].ToString();
            }
            List<VoteShowModel> ListVoteShow = new List<VoteShowModel>();
            List<VoteShowModel> VoteModel = new List<VoteShowModel>();
            PageModel<VoteShowModel> xx = new PageModel<VoteShowModel>();
            xx.PageSize = 6;
            xx.PageIndex = PageIndex;
            if (VoteNumberId == -1)
            {
                RedisCommon.GetPageListByRedis<VoteShowModel>(ref xx);
            }
            else
            {
                RedisCommon.GetPageListByRedisConditions<VoteShowModel>(ref xx, VoteNumberId, userName, limitVoteNum);
            }

            ListVoteShow = xx.ObjectList;

            List<VoteNumber> VoteNu = RedisCommon.GetListByRedis<VoteNumber>();
            ListVotesShowModel listVoteShow = new ListVotesShowModel();
            listVoteShow.VoteModel = ListVoteShow;
            listVoteShow.Total = xx.Total;
            int xxx = (xx.Total / 6) + 1;
           // listVoteShow.CurrentPage = PageIndex;
            if (xxx < PageIndex)
            {
                listVoteShow.CurrentPage = -1;
                return Json(listVoteShow, JsonRequestBehavior.AllowGet);
            }
            else {
                listVoteShow.CurrentPage = PageIndex;
                return Json(listVoteShow, JsonRequestBehavior.AllowGet);          
            }
        }


        /// <summary>
        /// 节目详情
        /// </summary>
        /// <returns></returns>
       [WeixinFilter]
        public ActionResult FestivalDetail(int VoteShowId, int canVoteType = 0, int page = 1, double scrollNum=0)
        {
            #region 是否关注

            string openId_ = Session["OpenId"].ToString();

            bool isSubscribe = IsSubscribe(openId_);

            ViewBag.isSubscribe = isSubscribe;

            #endregion

            string userName = null;
            if (Session["userName"] != null)
            {
                userName = Session["userName"].ToString();
            }
            FestivalModel fm = new FestivalModel();
            string VoteKey = "urn:voteshowmodel:" + VoteShowId;
            fm.VoteShowMo = RedisCommon.GetSimpleByRedis<VoteShowModel>(VoteKey);
            fm.VoteShowMo.Describle = System.Web.HttpUtility.HtmlDecode(fm.VoteShowMo.Describle);
            fm.VoteVi = RedisCommon.GetListByRedis<VoteVideoUrl>().Where(t => t.ShowId == VoteShowId).ToList();
            CanVoteModel cc = BllVoteNumber.GetFestivalDetail(VoteShowId, userName, limitVoteNum);
            fm.VoteShowMo.VoteNum = cc.voteNum;
            fm.canVoteType = cc.canVoteType;
            ViewBag.Model = fm;
            ViewBag.page = page;
            ViewBag.scrollNum = scrollNum;
            ViewBag.voteShowId = VoteShowId;
            return View();
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <returns></returns>
        public JsonResult SearchFestival(string FestName, int VoteNumberId)
        {
            List<VoteShowModel> ListVoteShow = RedisCommon.GetListByRedis<VoteShowModel>();
            List<VoteShowModel> VoteModel = new List<VoteShowModel>();
            //获取用户名
            string userName = "";
            if (Session["userName"] != null)
            {
                userName = Session["userName"].ToString();
            }

            #region 从数据库获取用户对应的投票状态和节目票数，插入到model里面
            List<CanVoteModel> cvm = BllVoteNumber.GetSimpleVote(FestName, userName, limitVoteNum, VoteNumberId);
            if (ListVoteShow.Count > 0 && cvm.Count > 0)
            {
                foreach (var listvote in ListVoteShow)
                {
                    foreach (var voteDb in cvm)
                    {
                        if (voteDb.showId == listvote.Id)
                        {
                            listvote.VoteNum = voteDb.voteNum;
                            listvote.canVoteType = voteDb.canVoteType;
                            VoteModel.Add(listvote);
                        }
                    }
                }
            }
            #endregion

            return Json(VoteModel.OrderByDescending(t => t.VoteNum), JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 微信电脑端打开
        /// </summary>
        /// <returns></returns>
        public ActionResult ComputerCode()
        {
            return View();
        }
        /// <summary>
        /// 赛事规则
        /// </summary>
        /// <returns></returns>
        public ActionResult Regulation()
        {
            return View();
        }
        /// <summary>
        /// 投票操作
        /// </summary>
        /// <param name="showId"></param>
        /// <returns></returns>
        public JsonResult VoteByUser(long showId)
        {
            string returnUrl = UserLogin();
            LogHelper.WriteInfoLog("投票判断用户是否登录："+returnUrl);
            ResultToVote retultTo = new ResultToVote();
            if (string.IsNullOrEmpty(returnUrl))
            {
                string userName = Session["userName"].ToString();
                int limitVoteNum = int.Parse(ConfigurationManager.AppSettings["limitVoteNum"]);

                VoteRecordModel xx1 = new VoteRecordModel();
                xx1.ShowId = showId;
                xx1.UserName = userName;
                xx1.LimitVoteNum = limitVoteNum;
                string resultVote = Voting(xx1);

                #region 送优惠券判断，发送
                string sql = "SELECT COUNT(id) FROM VoteRecord WHERE UserName='" + userName + "'";
                long count = BllVoteNumber.GetCountBySQL("VoteRecord", sql);
                //第一次投票就发送
                if (count == 1)
                {
                    string url = apiJson + "/VoteSendCoupon?userName=" + userName;
                    string json = WebUtils.DoGet(url, null);
                    retultTo.result = SerializeTool.DeSerialize<Result<string>>(json);
                }
                string[] temps = resultVote.Split(',');
                retultTo.VoteNum = temps[0].ConToInt();
                if (retultTo.VoteNum > 0)
                {
                    retultTo.LeaveVoteNum = limitVoteNum - (temps[1].ConToInt() + 1);
                }
                else
                {
                    retultTo.LeaveVoteNum = limitVoteNum - temps[1].ConToInt();
                }
                retultTo.returnUrl = "";
                #endregion

                return Json(retultTo, JsonRequestBehavior.AllowGet);
            }
            else
            {
                retultTo.returnUrl = returnUrl;
                return Json(retultTo, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 投票场次选择
        /// </summary>
        /// <param name="VoteNumberId"></param>
        /// <returns></returns>
        //public JsonResult VoteSwitch(int VoteNumberId)
        //{
        //    string userName = null;
        //    if (Session["userName"] != null)
        //    {
        //        userName = Session["userName"].ToString();
        //    }
        //    List<VoteShowModel> ListVoteShow = new List<VoteShowModel>();
        //    PageModel<VoteShowModel> xx = new PageModel<VoteShowModel>();
        //    xx.PageSize = 10;
        //    xx.PageIndex = 1;
        //    //RedisCommon.GetPageListByRedis<VoteShowModel>(ref xx);
        //    if (VoteNumberId == -1)
        //    {
        //        RedisCommon.GetPageListByRedis<VoteShowModel>(ref xx);
        //    }
        //    else
        //    {
        //        RedisCommon.GetPageListByRedisConditions<VoteShowModel>(ref xx, VoteNumberId);
        //    }
        //    ListVoteShow = xx.ObjectList;

        //    ListVotesShowModel ListShowModel = new ListVotesShowModel();
        //    List<VoteShowModel> VoteModel = new List<VoteShowModel>();
        //    //场次信息
        //    //VoteNumber vn=BllVoteNumber.SelectEntity<VoteNumber>("VoteNumber",VoteNumberId);
        //    string vni = "urn:votenumber:" + VoteNumberId;
        //    VoteNumber vn = RedisCommon.GetSimpleByRedis<VoteNumber>(vni);
        //    if (VoteNumberId != -1 && vn!=null)
        //    {
        //        ListShowModel.RemainVotes = BllVoteNumber.GetRemainVotes(VoteNumberId, userName, limitVoteNum);
        //        ListShowModel.StartTime = vn.StartTime.ToString("yyyy-MM-dd");
        //        ListShowModel.EndTime = vn.EndTime.ToString("yyyy-MM-dd");
        //    }
        //    #region 从数据库获取用户对应的投票状态和节目票数，插入到model里面

        //    List<CanVoteModel> cvm = BllVoteNumber.GetVotesByProceDure(VoteNumberId, userName, limitVoteNum);

        //    if (ListVoteShow!=null && cvm.Count > 0)
        //    {
        //        foreach (var listvote in ListVoteShow)
        //        {
        //            foreach (var voteDb in cvm)
        //            {
        //                if (voteDb.showId == listvote.Id)
        //                {
        //                    listvote.VoteNum = voteDb.voteNum;
        //                    listvote.canVoteType = voteDb.canVoteType;
        //                    VoteModel.Add(listvote);
        //                }
        //            }
        //        }
        //    }
        //    ListShowModel.VoteModel = VoteModel.OrderByDescending(a => a.VoteNum).ToList(); ;
        //    #endregion

        //    return Json(ListShowModel, JsonRequestBehavior.AllowGet);

        //}
        public string Voting(VoteRecordModel voteRe)
        {
            //投票操作
            string b = BllVoteCommon.VotingByProcedure(voteRe.ShowId, voteRe.UserName, voteRe.LimitVoteNum);

            return b;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        public string UserLogin()
        {
            LogHelper.WriteInfoLog("进入用户登录");
            string returnUrl = "";
            if (Session["OpenId"] == null)
            {
                if (Session["UserName"] == null)
                {
                    returnUrl = "/Home/Login";
                }
            }
            else
            {
                #region 通过微信进入
                string openId = Session["OpenId"].ToString();

                //string openId = "o8f7iwvE4y-jPi55QXeAx85u5QiY";
                bool flag = IsSubscribe(openId);
                if (!flag)
                {
                    //关注公众号二维码
                    //returnUrl = "/Home/ShowAttentionQRCode";
                    returnUrl = "code";
                }
                else
                {
                    string temp = GetUserName(openId);
                    if (!string.IsNullOrEmpty(temp))
                    {
                        returnUrl = temp;
                    }
                }
                #endregion
            }
            return returnUrl;
        }
        #endregion

        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public string GetUserName(string openId)
        {
            string userName = "";
            string returnUrl = "";
            LogHelper.WriteInfoLog("获取用户名开始");
            if (Session["UserName"] == null)
            {
                #region 先从缓存读取,查看是否有对应的用户
                var redisClient = RedisManager.GetClient();
                var userInfoModelList = redisClient.GetTypedClient<UserInfoForVote>();
                List<UserInfoForVote> listUserInfo = userInfoModelList.GetAll().ToList();
                LogHelper.WriteInfoLog("获取用户名缓存");
                foreach (UserInfoForVote model in listUserInfo)
                {
                    if (!string.IsNullOrEmpty(model.OpenId)&&model.OpenId.Equals(openId))
                    {
                        userName = model.UserName;
                        LogHelper.WriteInfoLog(openId+" 缓存命中用户名：" + model.UserName);
                        break;
                    }
                }
                #endregion

                #region 缓存查不到用户名再去数据库获取查询
                if (string.IsNullOrEmpty(userName))
                {
                    LogHelper.WriteInfoLog("用户名缓存没有命中");
                    string url = apiJson + "/GetUserNameByOpenId?openId=" + openId;
                    string json = WebUtils.DoGet(url, null);
                    Result<string> result = SerializeTool.DeSerialize<Result<string>>(json);
                    if (string.IsNullOrEmpty(result.Body))
                    {
                        //未注册用户,跳转到登录页
                        returnUrl = "/Home/Login";
                    }
                    else
                    {
                        LogHelper.WriteInfoLog(openId + " 数据库命中用户名：" + result.Body);
                        userName = result.Body;
                    }
                }
                #endregion

                if (!string.IsNullOrEmpty(userName))
                {
                    Session["UserName"] = userName;
                }
            }

            return returnUrl;
        }


        #region 注册

        /// <summary>
        /// 注册页面
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
         [WeixinFilter]
         [LoginFilter]
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 注册行为
        /// </summary>
        /// <returns></returns>
        public JsonResult RegisterAction(string phone, string password)
        {
            string openId = Session["OpenId"].ToString();
            string url = apiJson + "/Register?phone=" + phone + "&password=" + Encryption.EncryptMD5(password) + "&openId=" + openId;

            string json = WebUtils.DoGet(url, null);
            Result<string> result = SerializeTool.DeSerialize<Result<string>>(json);
            bool flag = false;
            string str = "";
            if (result.Body == "0")
            {
                str = "该手机已经注册！";
            }
            else if (result.Body == "1")
            {
                str = "注册成功";
                flag = true;
                Session["UserName"] = phone;
            }
            else if (result.Body == "2")
            {
                str = "注册失败！";
            }
            else
            {
                str = "注册失败！";
            }

            return Json(new { flag = flag, content = str }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 注册账户  发送短信
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public JsonResult SendRegisterMessage(string phone)
        {
            string url = apiJson + "/SendRegisterMessage?phone=" + phone;

            string json = WebUtils.DoGet(url, null);
            Result<string> result = SerializeTool.DeSerialize<Result<string>>(json);

            bool flag = false;
            string str = "";
            if (result.Body == "0")
            {
                str = "该手机已经注册！";
            }
            else if (result.Body == "1")
            {
                str = "短信发送成功,请留意手机接收到的手机短信！";
                flag = true;
            }
            else if (result.Body == "2")
            {
                str = "发送短信失败，请稍后再试！";
            }
            else
            {
                str = "发送短信失败，请稍后再试！";
            }

            return Json(new { flag = flag, content = str }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  验证 验证码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult SumitPhoneCode(string phone, string code)
        {
            string url = apiJson + "/SumitPhoneCode?phone=" + phone + "&code=" + code;

            string json = WebUtils.DoGet(url, null);
            Result<string> result = SerializeTool.DeSerialize<Result<string>>(json);
            bool flag = false;
            string str = "";
            if (result.Body == "0")
            {
                str = "该手机已经注册！";
            }
            else if (result.Body == "1")
            {
                str = "注册成功";
                flag = true;
            }
            else if (result.Body == "2")
            {
                str = "验证码不正确！";
            }
            else
            {
                str = "注册失败，请稍后再试！";
            }

            return Json(new { flag = flag, content = str }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 登录

        [WeixinFilter]
        [LoginFilter]
        public ActionResult Login()
        {
            string findPassword = weixinDomain + "/LoginManager/FindPassword?t=1";
            ViewBag.findPassword = findPassword;
            return View();
        }


        /// <summary>
        /// 登录提交
        /// </summary>
        /// <param name="Account"></param>
        /// <param name="Passwrod"></param>
        /// <returns></returns>
        public JsonResult UserInfoLogin(string userName, string password)
        {
            bool flag = false;
            string str = "";

            //性能测试时把这个注释掉
            password=Encryption.EncryptMD5(password);

            #region 先从缓存读取,查看是否有对应的用户
            var redisClient = RedisManager.GetClient();
            var userInfoModelList = redisClient.GetTypedClient<UserInfoForVote>();
            List<UserInfoForVote> listUserInfo = userInfoModelList.GetAll().ToList();
            foreach (UserInfoForVote model in listUserInfo)
            {
                if (model.UserName.Equals(userName) || (model.Phone != null && model.Phone.Equals(userName)))
                {
                    if (!string.IsNullOrEmpty(model.Password)&&model.Password.Equals(password))
                    {
                        str = "成功登录！";
                        flag = true;
                        Session["UserName"] = model.UserName;
                        LogHelper.WriteInfoLog("用户登录缓存命中用户名：" + model.UserName);
                    }
                    break;
                }
            }
            #endregion

            #region 缓存没命中则去数据库实时查询
            if (!flag)
            {
                string url = apiJson + "/UserInfoLogin?userName=" + userName + "&password=" + password;

                string json = WebUtils.DoGet(url, null);
                Result<string> result = SerializeTool.DeSerialize<Result<string>>(json);
                if (result.Body == "-3")
                {
                    str = "该用户已禁用！";
                }
                else if (result.Body == "-2")
                {
                    str = "用户名不存在！";
                }
                else if (result.Body == "-1")
                {
                    str = "密码错误！";
                }
                else
                {
                    str = "成功登录！";
                    flag = true;
                    Session["UserName"] = result.Body;
                }
            }
            #endregion

            #region 新开一个线程去更新openId,不阻塞主线程
            if (flag)
            {
                if (Session["OpenId"] != null)
                {
                    LogHelper.WriteInfoLog("登陆更改openId");
                    string openId = Session["OpenId"].ToString();
                    UpdateWeixinOpenIdRequest request = new UpdateWeixinOpenIdRequest();
                    request.openId = openId;
                    request.userName = Session["UserName"].ToString();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateWeixinOpenId), request);
                }
            }
            #endregion

            return Json(new { flag = flag, content = str }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新用户openId
        /// </summary>
        /// <param name="obj"></param>
        private void UpdateWeixinOpenId(object obj)
        {
            LogHelper.WriteInfoLog("进入多线程");
            UpdateWeixinOpenIdRequest request = (UpdateWeixinOpenIdRequest)obj;
            string url = apiJson + "/UpdateWeixinOpenId?userName=" + request.userName + "&openId=" + request.openId;
            LogHelper.WriteInfoLog("更新用户openId:" + url);
            string  json=WebUtils.DoGet(url, null);
            Result<bool> result = SerializeTool.DeSerialize<Result<bool>>(json);
            if (result.Status != 200)
            {
                LogHelper.WriteErrorLog("执行的sql语句报错："+result.Msg);
            }
        }
        public class UpdateWeixinOpenIdRequest
        {
            public string userName { get; set; }

            public string openId { get; set; }
        }

        #endregion

        #region 获取微信openId


        /// <summary>
        /// 展示关注公众号二维码
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowAttentionQRCode()
        {
            return View();
        }

        /// <summary>
        /// 获取用户的微信信息 未关注公众号：(先关注公众号) 已关注公众号：(未注册：先注册  已注册：进入投票界面)
        /// </summary>
        /// <param name="weiXinUserInfo"></param>
        /// <returns></returns>
        public ActionResult GetWeixinUserInfo(string openId, string returnUrl)
        {
            if (string.IsNullOrEmpty(openId))
            {
                LogHelper.WriteErrorLog("获取openId失败");
            }
            else
            {
                Session["OpenId"] = openId;

                Response.Redirect(returnUrl);
            }

            return null;
        }

        /// <summary>
        /// 判断用户是否关注公众号
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public bool IsSubscribe(string openId)
        {
            LogHelper.WriteInfoLog("获取用户关注信息开始");
            bool flag = false;

            #region 先从缓存读取,查看是否关注
            var redisClient = RedisManager.GetClient();
            var subcribeModelList = redisClient.GetTypedClient<SubcribeModel>();
            List<SubcribeModel> ListSubcribe = subcribeModelList.GetAll().ToList();
            LogHelper.WriteInfoLog("获取用户关注信息缓存");
            //LogHelper.WriteInfoLog("用户的关注信息：" + SerializeTool.ScriptSerialize<List<SubcribeModel>>(ListSubcribe));
            foreach (SubcribeModel model in ListSubcribe)
            {
                if (!string.IsNullOrEmpty(model.openId)&&model.openId.Equals(openId))
                {
                    if (!string.IsNullOrEmpty(model.follow)&&model.follow.Equals("1"))
                    {
                        flag = true;
                        LogHelper.WriteInfoLog("关注缓存命中用户：" + openId);
                    }
                    break;
                }
            }
            #endregion

            #region 如果缓存显示未关注,再去接口实时获取是否关注
            if (!flag)
            {
                LogHelper.WriteInfoLog("户关注信息缓存没有命中");
                string urlForDetetiveSubscribe = weixinDomain + "/anrweixin/VoteGetopenid.php?openid=" + openId+"&uniacid=2";
                string str = WebUtils.DoGet(urlForDetetiveSubscribe, null);
                SubscribeReturn<FollowModel> result = new JavaScriptSerializer().Deserialize<SubscribeReturn<FollowModel>>(str);
                if (result.status == 200)
                {
                    if (result.body!=null&&!string.IsNullOrEmpty(result.body.follow) && result.body.follow.Equals("1"))
                    {
                        flag = true;
                        LogHelper.WriteInfoLog("关注接口命中用户：" + openId);
                    }
                }
            }
            #endregion

            return flag;
        }

        #region 工具
        public class SubscribeReturn<T> where T : class
        {
            public int status { get; set; }

            public T body { get; set; }
        }

        public class FollowModel
        {
            public string follow { get; set; }
        }
        #endregion

        #endregion
    }
}